// 参考：https://blog.csdn.net/m0_37911706/article/details/128057137

const port = 8081;
const WebSocket = require("ws");
var mes = {};   // json格式的消息，用于发给客户端。客户端目前只支持解析json格式的消息

const wss = new WebSocket.Server({port:port});
wss.on('connection', (ws, req) => {
    // 从url中解析userId
    let {url} = req;
    let [_, userId] = url.slice(0).split('/');
    ws.userId = userId; // 保持起来，后面要用
    console.log(`websocket onconnection userId: ${userId}`);

    mes.type = 'enter';
    mes.data = `${userId} 加入房间`;
    broadcast(JSON.stringify(mes));

    ws.on('message', (message) => {
        console.log(`websocket onmessage: ${message}`);

        mes.type = 'message';
        mes.data = `${message}`;
        mes.sender = ws.userId;
        broadcast(JSON.stringify(mes));
    });

    ws.on('close', () => {
        console.log(`websocket onclose`);

        mes.type = 'leave';
        mes.data = `${ws.userId} 离开房间`;
        broadcast(JSON.stringify(mes));
    })

    ws.on("error", (error) => {
        console.log(`websocket on error: ${error}`);
    });
});

function broadcast(message){
    wss.clients.forEach((client) => {
        if(client.readyState == WebSocket.OPEN){
            client.send(message, (err) => {
                if(err){
                    console.log(`websocket send message error: ${err}`);
                }
            });
        }
    });
}